/**
 * 在线编辑
 */

var map;
var myview;
var vectorLayer;
var format = new ol.format.WKT();
var vectorSource;
var lvectorSource;
var pvectorSource;
var count;
var vector_layer;
var lvector_layer; 
var pvector_layer ;

$("document").ready(function() {
	queryPolygondata();
	queryPointdata();
	queryLinedata();
	
});

// 自定义了一个Map对象，类似Java里的Map 对象
var vecLayers = new Map();

vectorSource = new ol.source.Vector();
pvectorSource=new ol.source.Vector();
lvectorSource=new ol.source.Vector();

myview = new ol.View({
	center : [ 11842307, 4098936 ],
	zoom : 3
});

/**
 * 地图容器
 */

var map = new ol.Map(
		{
			layers : [
					new ol.layer.Group(
							{'title' : '基础底图',
							layers : [
							new ol.layer.Tile(
									{
										title : '天地图影像',
										type : 'base',
										source : new ol.source.XYZ(
												{
													url : 'http://t3.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}'
												})
									}),
							new ol.layer.Tile(
							{
								title : ' 必应影像',
								type : 'base',
								source :  new ol.source.BingMaps({
									         imagerySet: 'Aerial',
					             	         key: 'AkGbxXx6tDWf1swIhPJyoAVp06H0s0gDTYslNWWHZ6RoPqMpB9ld5FY1WutX8UoF'
										})
							})
				       	]
								}),
							
//					 new ol.layer.Group(
//							{
//							title : '叠加图层',
//							layers : [
//									new ol.layer.Tile(
//									{
//										title : '天地图注记',
//										source : new ol.source.XYZ(
//												{
//													url : 'http://t3.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}'
//												})
//
//									}),
//									
//									],
//							})
					 
					 ],

			target:'map',
			view : new ol.View({
                projection:"EPSG:3857",
				center : [11842307, 4098936],
				zoom : 3

			})
		});
var layerSwitcher = new ol.control.LayerSwitcher({
	tipLabel : '图层管理' // Optional label for button
});
map.addControl(layerSwitcher);


/**
 * 初始化图层
 */
var tian_di_tu_road_layer = new ol.layer.Tile({
	title : "天地图路网",
	source : new ol.source.XYZ({
		url : "http://t4.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}"
	})
});


var tian_di_tu_annotation = new ol.layer.Tile({
	title : "天地图文字标注",
	source : new ol.source.XYZ({
		url : 'http://t3.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}'
	})
});
var tian_di_tu_satellite_layer = new ol.layer.Tile({
	title : "天地图卫星影像",
	source : new ol.source.XYZ({
		url : 'http://t3.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}'
	})
});

/**
 * 创建面矢量图层
 */
vector_layer = new ol.layer.Vector({
	title:"面要素",
	name : '多边形图层',
	source : vectorSource, // 加载数据源
	style : new ol.style.Style({
		fill : new ol.style.Fill({
			color : 'rgba(255, 255, 255, 0.2)'
		}),
		stroke : new ol.style.Stroke({
			color : '#ffcc33',
			width : 2
		}),
		image : new ol.style.Circle({
			radius : 7,
			fill : new ol.style.Fill({
				color : '#ffcc33'
			})
		})
	})
});
map.addLayer(vector_layer);

/**
 * 创建线矢量图层
 */
 lvector_layer= new ol.layer.Vector({
	 title:"线要素",
	name : '线图层',
	source : lvectorSource, // 加载数据源
	style : new ol.style.Style({
		fill : new ol.style.Fill({
			color : 'rgba(255, 255, 255, 0.2)'
		}),
		stroke : new ol.style.Stroke({
			color : '#ffcc33',
			width : 2
		}),
		image : new ol.style.Circle({
			radius : 7,
			fill : new ol.style.Fill({
				color : '#ffcc33'
			})
		})
	})
});
map.addLayer(lvector_layer);

/**
 * 创建点矢量图层
 */
pvector_layer= new ol.layer.Vector({
	title:"点要素",
	name : '点图层',
	source : pvectorSource, // 加载数据源
	style : new ol.style.Style({
		fill : new ol.style.Fill({
			color : 'rgba(255, 255, 255, 0.2)'
		}),
		stroke : new ol.style.Stroke({
			color : '#ffcc33',
			width : 2
		}),
		image : new ol.style.Circle({
			radius : 4,
			fill : new ol.style.Fill({
				color : '#ffcc33'
			})
		})
	})
});
map.addLayer(pvector_layer);


/**
 * 面 绘制查询结果到矢量图层
 */
function drawWktFeatures(data, zoomlevel) {
	count=data.length;
	var wktformate = new ol.format.WKT();
	$.each(data, function(i, n) {
		var id = n.id;
		var wkt = n.geom;
		
		var feature = wktformate.readFeature(wkt, {
			dataProjection : 'EPSG:4326',
			featureProjection : 'EPSG:3857'
		});
		feature.setId(id);
		drawFeature(feature);
	});

	var extent = vectorSource.getExtent();
	map.getView().setZoom(zoomlevel);
	map.getView().setCenter(ol.extent.getCenter(extent));
}

	
	
/**
 * 点 绘制查询结果到矢量图层
 */
function drawPointWktFeatures(data, zoomlevel) {
	count=data.length;
	var wktformate = new ol.format.WKT();
	$.each(data, function(i, n) {
		var id = n.id;
		var wkt = n.geom;
		
		var feature = wktformate.readFeature(wkt, {
			dataProjection : 'EPSG:4326',
			featureProjection : 'EPSG:3857'
		});
		feature.setId(id);
		drawPointFeature(feature);
	});
}

/**
 * 线 查询结果到矢量图层
 */
function drawLineWktFeatures(data, zoomlevel) {
	
	var wktformate = new ol.format.WKT();
	$.each(data, function(i, n) {
		var id = n.id;
		var wkt = n.geom;
		
		var feature = wktformate.readFeature(wkt, {
			dataProjection : 'EPSG:4326',
			featureProjection : 'EPSG:3857'
		});
		feature.setId(id);
		drawLineFeature(feature);
	});
}	


/**
 * 面 添加要素到图层数据源
 */
function drawFeature(feature) {
	if (vectorSource) {
		vectorSource.addFeature(feature);
	}
}

/**
 * 点 添加要素到图层数据源
 */
function drawPointFeature(feature) {
	if (pvectorSource) {
		pvectorSource.addFeature(feature);
	}
}

/**
 * 线 添加要素到图层数据源
 */
function drawLineFeature(feature) {
	if (lvectorSource) {
		lvectorSource.addFeature(feature);
	}
}	
	
	
/** ***************面交互***************** */
var select_interaction, draw_interaction, modify_interaction;

// 面 创建选择交互
select_interaction = new ol.interaction.Select({
	// 操作图层
	layers : function(vector_layer) {
		return vector_layer.get('name') === '多边形图层';// 选择多边形图层
	}
});

/** ***************点交互***************** */
// 点交互
var pselect_interaction,pdraw_interaction, pmodify_interaction;
// 创建选择交互
pselect_interaction = new ol.interaction.Select({
	// 操作图层
	layers : function(pvector_layer) {
		return pvector_layer.get('name') === '点图层';// 选择多边形图层
	}
});

/** ***************线交互***************** */
	var lselect_interaction, ldraw_interaction, lmodify_interaction;

	// 线 创建选择交互
	lselect_interaction = new ol.interaction.Select({
		// 操作图层  此处要注意修改 
		layers : function(lvector_layer) {
			return lvector_layer.get('name') === '线图层';// 选择多边形图层
		}
});


	// 线 创建新交互
	ldraw_interaction = new ol.interaction.Draw({
		source : lvector_layer.getSource(),
		type : /** @type {ol.geom.GeometryType} */
		('LineString')
	});
		/** ***************线交互结束***************** */
 
			
/**
 * 线 绘制
 * 
 */
function addDrawLineInteraction() {
	// 移除点交互
    map.removeInteraction(pselect_interaction);
    map.removeInteraction(pmodify_interaction);
    map.removeInteraction(pdraw_interaction);
    
    // 移除面交互
    map.removeInteraction(select_interaction);
    map.removeInteraction(modify_interaction);
    map.removeInteraction(draw_interaction);
    
    // 移除线 选择 修改
	map.removeInteraction(lselect_interaction);
	map.removeInteraction(lmodify_interaction);

	
	// 添加到地图
	map.addInteraction(ldraw_interaction);

	// 绘制结束
	ldraw_interaction.on('drawend', function(event) {
		$("#dialog").dialog();
		// 创建唯一id
		 var id=0;
		
		var data_type = /** @type {ol.geom.GeometryType} */
		('LineString'),
		// 数据转换格式
		format = new ol.format['WKT']({
			dataProjection:"4326",
			featureProjection:"3857"
		}), geom;
		try {
			geom = format.writeFeature(event.feature);
            geom=XYtoLonLat(geom);
			console.log(geom);

		} catch (e) {
			return;
		}
		var data = {
			geom : geom
		};
		$("#dpup").bind("click", data, savecldata);
	});
}

	
/**
 * 面 绘制
 * 
 * @returns
 */
function addDrawPolygonInteraction() {
	// 移除点交互
    map.removeInteraction(pselect_interaction);
    map.removeInteraction(pmodify_interaction);
    map.removeInteraction(pdraw_interaction);
    // 移除线交互
    map.removeInteraction(lselect_interaction);
    map.removeInteraction(lmodify_interaction);
    map.removeInteraction(ldraw_interaction);
    
    // 面 创建新交互
    draw_interaction = new ol.interaction.Draw({
	source : vector_layer.getSource(),
	type : /** @type {ol.geom.GeometryType} */
	('Polygon')
});
    
	map.removeInteraction(select_interaction);
	map.removeInteraction(modify_interaction);
	

	
	// 添加到地图
	map.addInteraction(draw_interaction);

	// 绘制结束
	draw_interaction.on('drawend', function(event) {
		
	$("#dialog").dialog();
		var data_type = /** @type {ol.geom.GeometryType} */
		('Polygon'),
		// 数据转换格式
		format = new ol.format['WKT']({
			dataProjection:"4326",
			featureProjection:"3857"
		}), geom;
		try {
		    geom = format.writeFeature(event.feature);
			geom=XYtoLonLat(geom);
			
		} catch (e) {
			return;
		}
		
		var data = {
			geom : geom
		};
		$("#dpup").bind("click", data, savecdata);
	});
}

/**
 * 点 绘制
 * 
 * @returns
 */
function addDrawPointInteraction() {
	// 移除面他交互
    map.removeInteraction(select_interaction);
    map.removeInteraction(modify_interaction);
    map.removeInteraction(draw_interaction);
    
    // 移除线交互
    map.removeInteraction(lselect_interaction);
    map.removeInteraction(lmodify_interaction);
    map.removeInteraction(ldraw_interaction);
    
	map.removeInteraction(pselect_interaction);
	map.removeInteraction(pmodify_interaction);

	// 创建新交互
	pdraw_interaction = new ol.interaction.Draw({
		source : pvector_layer.getSource(),
		type : /** @type {ol.geom.GeometryType} */
		('Point')
	});
	// 添加到地图
	map.addInteraction(pdraw_interaction);

	// 绘制结束
	pdraw_interaction.on('drawend', function(event) {
		
		$("#dialog").dialog();
		// 创建唯一id
		 var id=0;
		
		var data_type = /** @type {ol.geom.GeometryType} */
		('Polygon'),
		// 数据转换格式
		format = new ol.format['WKT']({
			dataProjection:"4326",
			featureProjection:"3857"
		}), geom;
		try {
			geom = format.writeFeature(event.feature);
            geom=XYtoLonLat(geom);
			console.log(geom);
		} catch (e) {
			return;
		}
		var data = {
			id : id + "",
			geom : geom
		};

		$("#dpup").bind("click", data, savecpdata);
		geom="";
	});
}



/**
 * 
 * 面 修改
 * 
 * @returns
 */

//
function addModifyPgon() {
	// 移除点交互
	map.removeInteraction(pselect_interaction);
	map.removeInteraction(pmodify_interaction);
	map.removeInteraction(pdraw_interaction);
	
	// 图层交互是否激活
	pselect_interaction.setActive(false);
	lselect_interaction.setActive(false);
	select_interaction.setActive(true);
	
	map.removeInteraction(draw_interaction);
	
	// 地图添加选择交互
	map.addInteraction(select_interaction);
	// 获取要修改的要素
	var selected_features = select_interaction.getFeatures();

	// 选择一个要素 执行 事件
	selected_features.on('add', function(event) {
		// 获取要素
		var feature = event.element;

		// 监听变化并保存数据
		// feature.on('d', saveData);
		modify_interaction.on('modifyend',saveData);

		// 监听delete按键事件
		$(document).on(	'keyup',function(event) {
				
			      /** 删除事件开始* */
			      if (event.keyCode == 46) {
						// 删除
						selected_features.forEach(function(selected_feature) {
							var selected_feature_id = selected_feature.getId();
							// 删除 select_interaction
							selected_features.remove(selected_feature);
							// features aus vectorlayer entfernen
							var vectorlayer_features = vector_layer.getSource()
									.getFeatures();
							vectorlayer_features.forEach(function(
									source_feature) {
								var source_feature_id = source_feature.getId();
								if (source_feature_id === selected_feature_id) {
									// remove from my_vectorlayer
									vector_layer.getSource().removeFeature(
											source_feature);
									// 保存到数据库
									savedata();
								}
							});
						});
						// 移除监听
						$(document).off('keyup');
					}
			      /** 删除结束* */
				});
		
	});

	modify_interaction = new ol.interaction.Modify({
		features : selected_features,
		// 按shift删除拐点的同时鼠标单击
		deleteCondition : function(event) {
			return ol.events.condition.shiftKeyOnly(event)
					&& ol.events.condition.singleClick(event);
		}
	});
	map.addInteraction(modify_interaction);
}


/**
 * 点 修改
 * 
 * @returns
 */
function addModifyPoint() {
	// 移除面交互
	map.removeInteraction(select_interaction);
	map.removeInteraction(modify_interaction);
	map.removeInteraction(draw_interaction);

    select_interaction.setActive(false);
    lselect_interaction.setActive(false);
    pselect_interaction.setActive(true);

   
	map.removeInteraction(pdraw_interaction);
	
	// 地图添加选择交互
	map.addInteraction(pselect_interaction);
	// 获取要修改的要素
	var selected_features = pselect_interaction.getFeatures();

	// 选择一个要素 执行 事件
	selected_features.on('add', function(event) {
		// 获取要素
		var feature = event.element;

		// 监听变化并保存数据
		 // feature.on('change', saveData);
		pmodify_interaction.on('modifyend',psaveData);

		// 监听按键事件
		$(document).on(	'keyup',function(event) {
			      /** 删除事件开始* */
			      if (event.keyCode == 46) {
						// 删除
						selected_features.forEach(function(selected_feature) {
							var selected_feature_id = selected_feature.getId();
							// 删除 select_interaction
							selected_features.remove(selected_feature);
							// 选择的图层
							var vectorlayer_features = pvector_layer.getSource()
									.getFeatures();
							vectorlayer_features.forEach(function(
									source_feature) {
								var source_feature_id = source_feature.getId();
								if (source_feature_id === selected_feature_id) {
									// remove from my_vectorlayer
									pvector_layer.getSource().removeFeature(
											source_feature);
									// 保存到数据库
									savedata();
								}
							});
						});
						// 移除监听
						$(document).off('keyup');
					}
			   
				});
					   /** 删除结束* */
		
	});
	
	pmodify_interaction = new ol.interaction.Modify({
		features : selected_features,
		// 按shift删除拐点的同时鼠标单击
		deleteCondition : function(event) {
			return ol.events.condition.shiftKeyOnly(event)
					&& ol.events.condition.singleClick(event);
		}
	});
	map.addInteraction(pmodify_interaction);
}


/**
 * 线 修改
 * 
 */

function addModifyLine() {
	// 移除点交互
	map.removeInteraction(pselect_interaction);
	map.removeInteraction(pmodify_interaction);
	map.removeInteraction(pdraw_interaction);
	
	// 移除面交互
	map.removeInteraction(select_interaction);
	map.removeInteraction(modify_interaction);
	map.removeInteraction(draw_interaction);
	
	pselect_interaction.setActive(false);
	select_interaction.setActive(false);
	lselect_interaction.setActive(true);
	
	map.removeInteraction(ldraw_interaction);
	
	// 地图添加选择交互
	map.addInteraction(lselect_interaction);
	// 获取要修改的要素
	var selected_features = lselect_interaction.getFeatures();

	// 选择一个要素 执行 事件
	selected_features.on('add', function(event) {
		// 获取要素
		var feature = event.element;

		// 监听变化并保存数据
		
		lmodify_interaction.on('modifyend',lsaveData);

		// 监听delete按键事件
		$(document).on(	'keyup',function(event) {
				
			      /** 删除事件开始* */
			      if (event.keyCode == 46) {
						// 删除
						selected_features.forEach(function(selected_feature) {
							var selected_feature_id = selected_feature.getId();
							// 删除 select_interaction
							selected_features.remove(selected_feature);
							// features aus vectorlayer entfernen
							var vectorlayer_features = lvector_layer.getSource()
									.getFeatures();
							vectorlayer_features.forEach(function(
									source_feature) {
								var source_feature_id = source_feature.getId();
								if (source_feature_id === selected_feature_id) {
									// remove from my_vectorlayer
									lvector_layer.getSource().removeFeature(
											source_feature);
									// 保存到数据库
									savedata();
								}
							});
						});
						// 移除监听
						$(document).off('keyup');
					}
			      /** 删除结束* */
				});
		
	});

	lmodify_interaction = new ol.interaction.Modify({
		features : selected_features,
		// 按shift删除拐点的同时鼠标单击
		deleteCondition : function(event) {
			return ol.events.condition.shiftKeyOnly(event)
					&& ol.events.condition.singleClick(event);
		}
	});
	map.addInteraction(lmodify_interaction);
}

// 点
// 保存数据
function psaveData() {
	var format = new ol.format['WKT'](),
	// this will be the data in the chosen format
	geom;
	
	var features = pselect_interaction.getFeatures();
	var lastfeaute = features.item(0);
	try {
		geom = format.writeFeature(lastfeaute);
		geom=XYtoLonLat(geom);

	} catch (e) {

		return;
	}
	var data = {
			id : lastfeaute.getId()+"",
			geom : geom
		};
        $("#dialog").dialog();
		$("#dpup").bind("click", data, psaveudata);
}


// 线
// 保存数据
function lsaveData() {
	var format = new ol.format['WKT'](),
	// this will be the data in the chosen format
	geom;
	
	var features = lselect_interaction.getFeatures();
	var lastfeaute = features.item(0);
	try {
		geom = format.writeFeature(lastfeaute);
		geom=XYtoLonLat(geom);

	} catch (e) {

		return;
	}
	var data = {
			id : lastfeaute.getId()+"",
			geom : geom
		};
        $("#dialog").dialog();
		$("#dpup").bind("click", data, lsaveudata);
}

/**
 * 修改属性信息
 */
function addDescribtion(id){
	saveData();
}

// 点、线、面 属性保存
function saveData() {
	var format = new ol.format['WKT'](),
	features,
	geom,
	vselect,
	pselect,
	lselect;
	
	// * 判断哪个图层被选中
     vselect=select_interaction.getActive();
     pselect=pselect_interaction.getActive();
     lselect=lselect_interaction.getActive();
     
    if(vselect){
		features = select_interaction.getFeatures();
	}
	if(pselect){
		features = pselect_interaction.getFeatures();
	}
	if(lselect){
		features = lselect_interaction.getFeatures();
	}
	
	var lastfeaute = features.item(0);
	try {
		geom = format.writeFeature(lastfeaute);
		geom=XYtoLonLat(geom);

	} catch (e) {

		return;
	}
	var data = {
			id : lastfeaute.getId()+"",
			geom : geom
		};
        $("#dialog").dialog();
        
        if(vselect){
		$("#dpup").bind("click", data, saveudata);
        }
        if(pselect){
		$("#dpup").bind("click", data, psaveudata);
        }
        if(lselect){
		$("#dpup").bind("click", data,lsaveudata);
       }
}
